import {
  login,
  logout,
  getUserInfo,
  getMessage,
  getContentByMsgId,
  hasRead,
  removeReaded,
  restoreTrash,
  getUnreadCount
} from '@/api/user'
import { setToken, getToken } from '@/libs/util'

export default {
  state: {
    username: '',
    userId: '',
    avatarImgPath: '',
    token: getToken(),
    access: '',
    hasGetInfo: false
  },
  mutations: {
    setAvatar (state, avatarPath) {
      state.avatarImgPath = avatarPath
      sessionStorage.setItem('avatarImgPath', avatarPath)

    },
    setUserId (state, id) {
      state.userId = id
      sessionStorage.setItem('userId', id)
    },
    setUserName (state, name) {
      state.username = name
      sessionStorage.setItem('username', name)
    },
    setAccess (state, access) {
      state.access = access
      sessionStorage.setItem('access', access)

    },
    setToken (state, token) {
      state.token = token
      setToken(token)
    },
    setHasGetInfo (state, status) {
      state.hasGetInfo = status
    }
  },
  getters: {

  },
  actions: {
    // 登录
    handleLogin ({ commit }, { username, password }) {
      username = username.trim()
      return new Promise((resolve, reject) => {
        login({
          username,
          password
        }).then(res => {
          if(res.code === 1){
            commit('setToken', res.data.token)
            commit('setUserName', res.data.username)
            commit('setUserId', res.data.id)
            commit('setAccess', res.data.access)
            commit('setHasGetInfo', true)
          }
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 退出登录
    handleLogOut ({ state, commit }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('setToken', '')
          commit('setAccess', [])
          resolve()
        }).catch(err => {
          reject(err)
        })
        // 如果你的退出登录无需请求接口，则可以直接使用下面三行代码而无需使用logout调用接口
        // commit('setToken', '')
        // commit('setAccess', [])
        // resolve()
      })
    },
    // 获取用户相关信息
    getUserInfo ({ state, commit }) {
      return new Promise((resolve, reject) => {
        try {
          let access = sessionStorage.getItem('access')
          let data = {
            avator: sessionStorage.getItem('avatorImgPath'),
            name: sessionStorage.getItem('username'),
            user_id: sessionStorage.getItem('userId'),
            access: access !== '' ? access.split(',') : []
          }
          commit('setUserName', data.name)
          commit('setUserId', data.user_id)
          commit('setAccess', data.access)
          commit('setHasGetInfo', true)
          resolve(data)
        } catch (error) {
          reject(error)
        }
      })
    }
  }
}
